package cn.edu.sdjzu.xg.eagle.Controller;

import cn.edu.sdjzu.xg.eagle.Service.OrganizationService;
import cn.edu.sdjzu.xg.eagle.Service.OrganizationServiceInterface;
import cn.edu.sdjzu.xg.eagle.entity.Organization;
import com.alibaba.fastjson2.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

@WebServlet("/organizations/tree")
public class OrganizationTreeCtl extends HttpServlet {

    private final OrganizationServiceInterface organizationServiceInterface = OrganizationService.getInstance();

    /**
     * /organizations/tree/parentId=?2
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String parentIdParam = request.getParameter("parentId");

        Long parentId = null;
        if (parentIdParam != null) {
            try {
                parentId = Long.parseLong(parentIdParam);
            } catch (NumberFormatException e) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                out.println(JSON.toJSONString("Parent ID格式错误"));
                return;
            }
        }

        Collection<Organization> organizations = organizationServiceInterface.findAllChildren(parentId);
        if (organizations != null) {
            String jsonString = JSON.toJSONString(organizations);
            out.println(jsonString);
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            out.println(JSON.toJSONString("未找到任何组织数据"));
        }
    }
}
